<% include ../common/top %>

<link rel="stylesheet" type="text/css" href="stylesheets/post.css"/>
<link rel="stylesheet" type="text/css" href="/javascripts/wangEditor.css"/>
    


<h2 class="text-center text-success"><a href="/">返回首页</a></h2>
<h2 class="text-center text-success">发表微博页面 </h2>

<div id="wrapper-editor">
    <input type="text" placeholder="请输入作者名字" id="author" class="form-control" />
    <br/>
    <input type="text" placeholder="请输入微博标题" id="wbTitle" class="form-control" />
    <br/>
    <div id="weditor">
        <p>请在此处编辑您的文章</p>
    </div>
    <div class="submitarea">
        <button id="post-weibo" class="btn btn-success">发表微博</button>

    </div>
</div>



<!-- <hr>
    <div class="form-group">
        <label for="modal_inputFile" class="col-md-3 control-label label-font">位置图:</label>
        <div class="col-md-9">
            <input type="file" id="modal_inputFile" class="form-control" accept="image/png,image/gif,image/jpg,image/jpeg"  multiple="multiple" />
        </div>
        <button id="previewimg" class="btn btn-success">预览</button>
        <button id="upimg" class="btn btn-primary">上传</button>
        <div id="previewImg"></div>
    </div>
<hr>


<div class="uploadKey">测试uploadKey</div> -->

<% include ../common/bottom %>
<script src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script>
<script type="text/javascript">
    // 发表微博
    var postWb = {
        init: function() {
            this.initWangEditor();
            this.r_init();
        },
        dom: {
            postWeibo: $("#post-weibo"),
            wbTitle: $("#wbTitle"),
            author: $("#author")
        },
        initWangEditor: function() {
            var E = window.wangEditor
            this.editor = new E('#weditor');
            this.editor.customConfig.uploadImgServer = "/post/uploadimg";  // 上传图片到服务器
            this.editor.customConfig.uploadImgParams = {
                token: window.upLoadToken
            }
            this.editor.customConfig.uploadFileName = 'file';

            // 上传图片各个阶段的钩子
            this.editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                    console.log("before:");
                },
                success: function (xhr, editor, result) {
                    console.log("success:");
                },
                fail: function (xhr, editor, result) {
                    console.log("fail:", result);
                },
                error: function (xhr, editor) {
                    console.log("error:");
                },
                timeout: function (xhr, editor) {
                    console.log("timeout:", success);
                },
            }
            this.editor.create();                  
            
        },

        postWb: function(){
            var content = this.editor.txt.html() || "未填写内容";
            var title = this.dom.wbTitle.val() || "未填写标题";
            var author = this.dom.author.val() || "未填写作者姓名";
            var data = {
                text: content,
                title: title,
                author: author,
                coverImg: 'http://pcb7ukio1.bkt.clouddn.com/1536847970000_61c67c0ec9a8ca2c0e6df4d9cd1c4b5f.jpeg',
                status: '1',
                createTime: new Date(),
            };
            console.log(data);
            ajaxRequest2("post", "/post/saveAticle", data, function (data) {
                if(data.msg) {
                    alert("恭喜您，发表成功！");
                } else {
                    alert("发表失败！请稍后再试！");
                }
            }, '');
        },
        r_init: function() {
            var me = this;
            this.dom.postWeibo.click(function() {
                me.postWb();
            });
        },
    }


    // 普通上传图片示例
    var uploadImgObject = {
        init: function(){
            this.r_init();
        },
        dom: {
            previewImg: $("#previewImg"),
            file: document.getElementById('modal_inputFile'),
            ib_pre: document.getElementById('modal-pre'),
            previewimg: $("#previewimg"),
            upimg: $("#upimg"),
        },
        previewimg() {
            var me = this;
            var file = this.dom.file.files;
            if (!file) return false;
            var fileArray=[].slice.call(file, 0);//类数组转换为数组
            console.log(fileArray);
            fileArray.forEach(function(file){
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    var imgs = '<img src=' +   e.target.result + ' class="img-responsive" id="modal-pre" alt="预览区" style="max-height: 300px">';
                    me.dom.previewImg.append(imgs);
                }
            });
        },
        // 支持多张图片上传，node 代码暂不支持上传
        upimg: function() {
            var file = this.dom.file.files;
            var data = new FormData();
            data.enctype="multipart/form-data";
            var fileArray=[].slice.call(file, 0);//类数组转换为数组
            fileArray.forEach(function(file){
                data.append("file", file);//循环遍历把文件对象插到formData对象上
            });
            ajaxRequest('post', '/post/uploadimg', data, '', '');
        },
        r_init: function() {
            var me = this;
            this.dom.previewimg.click(function(){
                me.previewimg();
            });
            this.dom.upimg.click(function(){
                me.upimg();
            })
        }
    }

    uploadImgObject.init();
    postWb.init();  // 富文本编辑器


    // 前端获取token代码
    $(".uploadKey").click(function() {
        ajaxRequest2('post', '/post/getUploadKey', {}, function(data) {
            localStorage.setItem("upLoadToken", data.data);
        })
    });
    
    function ajaxRequest(type, url, data, success, error) {
        $.ajax({
            type: type,
            dataType: 'json',
            url: url,
            data: data || {},
            contentType: false, //不设置内容类型， contentType设置为false。因为是由<form>表单构造的FormData对象，且已经声明了属性enctype="multipart/form-data"，所以这里设置为false。
            processData: false, //不处理数据， 是否序列化参数字符串， 因为data值是FormData对象，不需要对数据做处理。cache设置为false，上传文件不需要缓存。
            success: function(data) {
                console.log(data);
                success && success(data);
            },
            error: function(err) {
                console.log(err);
                error && error(err);
            }
        })
    }

    function ajaxRequest2(type, url, data, callback) {
        $.ajax({
            type: type,
            dataType: 'json',                     
            url: url,
            data: data,  
            cache: false,  
            success:function(data) {  
                callback && callback(data);
            },  
            error : function(err) {  
                console.log('err:', err); 
            }  
        });
    }

</script>

